<template>
  <div
    :class="[
      'card-container pr u-s',
      type === 'course' ? 'dark-type' : '',
      examType === 'common' ? 'fixed-right' : ''
    ]"
  >
    <template v-if="examType === 'common'">
      <img
        class="close-img cu"
        @click="closePage"
        src="//image.zlketang.com/public/news/others/imgs/web_pc/0b4e7a0e5fe84ad35fb5f95b9ceeac79.png"
      />
      <div class="dayi-title flex-center-wrap">答疑</div>
    </template>
    <!-- 顶部tab -->
    <div class="flex-center-wrap tab-container">
      <template v-if="!showDetail">
        <span
          v-for="(item, index) in tabBtn"
          :key="item"
          class="tab-btn"
          :class="{ 'active-tab': activeTab === index }"
          @click="changeTab(index)"
        >
          {{ item }}
        </span>
      </template>
      <span v-show="showDetail" class="flex-center-wrap back-btn ">
        <span class="flex-center" @click="showDetail = false">
          <zl-icon
            class="pointer"
            icon="icon-zuojiantou-copy"
            :icon-style="{ width: '12px', height: '20px', color: '#999' }"
          ></zl-icon>
        </span>
        <span class="ml12 select-none">提问详情</span>
      </span>
      <span v-if="jumpToDayi" class="question-btn" @click="jumpToDayiBtn">
        去提问
      </span>
    </div>
    <!-- 列表 -->
    <template v-if="!showDetail">
      <div
        v-if="questionList.length && questionList[activeTab].length"
        class="mt26 overflow-scroll"
      >
        <button
          class="question-card pointer"
          v-for="item in questionList[activeTab]"
          :key="'qa_' + item.object_id"
          @click="getQuestionDetail(item)"
          :disabled="clickLock"
          :class="{ unread: activeTab === 1 && item.is_unread }"
        >
          <div class="card-title-info text-ess-2">
            <span
              class="question-status scale-83"
              :class="{
                'blue-status':
                  [1, 3].includes(item.question_status) && activeTab === 1
              }"
            >
              {{
                activeTab === 0
                  ? '精华'
                  : [1, 3].includes(item.question_status)
                  ? '已解答'
                  : '待解答'
              }}
            </span>
            {{ item.question_info }}
          </div>
          <div class="card-reply-info mt16" v-show="activeTab === 0">
            <div class="flex-center-wrap">
              <img
                class="card-teacher-header mr4"
                :src="parseResourceUrl(item.teacher_avatar)"
                alt="头像"
              />
              <span class="card-teacher-name list-teacher-name text-ess-1 mr4">
                {{ item.teacher_name }}
              </span>
              <span class="card-teacher-tag scale-83">
                答疑老师
              </span>
            </div>
            <div class="card-teacher-reply mt10 text-ess-2">
              {{ item.reply_info }}
            </div>
          </div>
          <div class="card-bottom-info flex-center-wrap flex-justify-between">
            <span
              :class="{ 'c-ff7819': [1, 2].includes(+item.question_status) }"
            >
              {{
                judgeTime(
                  item.create_time,
                  item.question_status,
                  item.expire_seconds
                )
              }}
            </span>
            <span class="flex-center-wrap">
              <span
                class="pointer flex-center-wrap mr20"
                @click.stop="giveThumbAndCollect(item, 'collect')"
              >
                <zl-icon
                  icon="icon-shoucangxingxing"
                  :icon-style="{
                    width: '16px',
                    height: '16px',
                    color: item.is_collect ? '#FFCA42' : '#d8d8d8'
                  }"
                ></zl-icon>
                <span class="ml2 collect-thumb">
                  {{ +item.is_collect === 1 ? '已收藏' : '收藏' }}
                </span>
              </span>
              <span
                class="pointer flex-center-wrap"
                @click.stop="giveThumbAndCollect(item, 'thumb')"
              >
                <zl-icon
                  icon="icon-a-dianzanxuanzhong"
                  :icon-style="{
                    width: '14px',
                    height: '14px',
                    color: item.is_thumbs ? '#ff5338' : '#d8d8d8'
                  }"
                ></zl-icon>
                <span class="ml2 collect-thumb">
                  {{ personNum(item.thumbs_num) }}
                </span>
              </span>
            </span>
          </div>
        </button>
      </div>
      <div v-else class="no-data">
        <div class="flex-center flex-column-wrap">
          <img
            :src="
              type === 'course'
                ? '//image.zlketang.com/public/news/images/new_official/play/empty.png'
                : '//image.zlketang.com/public/news/images/new_official/play/empty_white.png'
            "
            alt="空状态"
            class="empty-img"
          />
          <div class="empty-text">
            {{ activeTab ? '暂无我的提问记录哦' : '暂无答疑记录哦' }}
          </div>
        </div>
      </div>
    </template>
    <!-- 详情 -->
    <div v-if="showDetail" class="overflow-scroll detail-container">
      <div
        v-for="(item, index) in questionDetail"
        class="detail-card mb24"
        :key="'detail_' + index"
      >
        <div class="flex-center-wrap">
          <img
            class="card-teacher-header mr4"
            :src="
              parseResourceUrl(
                item.teacher_avatar ||
                  userInfo.user_avatar ||
                  '//image.zlketang.com/public/news/images/guanwangPic/user-default.png'
              )
            "
            alt="头像"
          />
          <span class="card-teacher-name text-ess-1 mr4">
            {{ item.teacher_name || userInfo.user_name || '之了' }}
          </span>
          <span class="card-teacher-tag scale-83" v-if="item.teacher_name">
            答疑老师
          </span>
          <span class="card-teacher-tag orange scale-83" v-else-if="index > 0">
            追问
          </span>
        </div>
        <div
          class="mt10 detail-question-text"
          :class="{ 'c-b3': item.reply_content }"
        >
          {{ item.question || item.reply_content }}
        </div>
        <div
          class="flex-wrap flex-justify-between flex-multi-row"
          v-if="Array.isArray(item.imgs_url || item.reply_imgs_url)"
        >
          <el-image
            v-for="(img, index) in item.imgs_url"
            :key="img.create_time + index"
            class="question-img mt10"
            :src="parseResourceUrl(img)"
            :preview-src-list="parseResourceUrlAll(item.imgs_url)"
            :initial-index="index"
            fit="cover"
            :lazy="true"
          ></el-image>
        </div>
        <div class="create-time mt10">{{ item.create_time }}</div>
      </div>
    </div>
    <!-- 收藏成功弹窗 -->
    <div class="collect-dialog flex-center" v-if="showCollectDialog">
      <div class="collect-dialog-box">
        <div class="collect-dialog-box-font  ">
          本条答疑收藏成功，可在
          <span class="color-ff8d">APP</span>
          「个人
        </div>
        <div class="collect-dialog-box-font ">
          中心-笔记/收藏-我的收藏」查看
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import zlIcon from '@/components/zlIcon.vue'

import {
  getTabQuestionList,
  thumbAndCollect,
  getQuestionDetail
} from '@/api/answer_question'
export default {
  name: 'daYi',
  components: {
    zlIcon
  },
  props: {
    examType: {
      type: String,
      default: ''
    },
    type: {
      type: String, // 题库-exam 课程-course
      required: true
    },
    keyId: {
      type: Number, // 题库id 课程id
      required: true
    },
    jumpToDayi: {
      type: Function
    },
    keyContent: {
      type: String
    }
  },
  data() {
    return {
      clickLock: false, // 点击锁
      tabBtn: ['常见问题', '我的问题'], // tab按钮
      showDetail: false, // 是否显示详情
      activeTab: 0, // 当前选中的tab
      questionList: [], // 问题列表
      //点赞收藏的节流
      thumbMap: {},
      collectMap: {},
      //防止重复点击
      isClickDetail: false,
      questionDetail: {}, // 问题详情
      userInfo: {}, // 用户信息
      zlaBtn: {
        key_name: '',
        key_content: ''
      },
      showCollectDialog: false //收藏成功弹窗
    }
  },
  methods: {
    closePage() {
      this.$emit('analysisPageChange', {
        page: ''
      })
    },
    // 初始化
    init() {
      if (!this.keyId) {
        return
      }
      // 重置数据
      this.clickLock = false
      this.showDetail = false
      this.activeTab = 0
      this.questionList = []
      this.thumbMap = {}
      this.collectMap = {}
      this.isClickDetail = false
      this.questionDetail = {}
      this.userInfo = {}
      this.showCollectDialog = false

      this.getQuestionList()
    },
    jumpToDayiBtn() {
      this.zlaBtn = {
        key_name: '去提问',
        key_content: this.keyContent || ''
      }
      this.jumpToDayi && this.jumpToDayi()
    },
    // 切换tab
    changeTab(index) {
      this.zlaBtn = {
        key_name: this.tabBtn[index],
        key_content: this.keyContent || ''
      }
      this.activeTab = index
      this.getQuestionList()
    },
    // 处理点赞人数
    personNum(num) {
      if (+num > 10000) {
        return (+num / 10000).toFixed(1) + '万'
      }
      return num
    },
    // 获取列表
    getQuestionList() {
      if (this.clickLock) return
      this.clickLock = true
      getTabQuestionList({ pre_key: this.type, ukey: this.keyId })
        .then(res => {
          let { data } = res
          let { normal_list, my_solution } = data || {}
          this.questionList = [normal_list || [], my_solution || []]
          this.clickLock = false
        })
        .catch(err => {
          this.clickLock = false
        })
    },
    //处理问题时间显示 0-待解答未结束 1-已解答未结束 2-追问待解答未结束 3-已解答已结束 4-待解答已结束 5-追问待解答已结束
    judgeTime(createTime, status, seconds) {
      if (!createTime) return
      createTime = this.timeFormat(
        'Y-m-d H:i',
        new Date(createTime.replace(/-/g, '/')).getTime() / 1000
      )
      if ([1, 2].includes(+status)) {
        if (seconds > 600) {
          return `${(+seconds / 3600).toFixed(1)}小时后提问将被关闭`
        }
        return `${(+seconds / 60).toFixed(1)}分钟后提问将被关闭`
      }
      return `${createTime + ' 提问'}`
    },
    //点赞和收藏
    giveThumbAndCollect(item, type) {
      // if((type === 'collect' && this.collectMap[item.object_id]) || (type === 'thumb' && this.thumbMap[item.object_id])) return

      let status = 1
      if (type === 'collect') {
        this.collectMap[item.object_id] = true
        status = item.is_collect ? 2 : 1
        item.is_collect = +item.is_collect === 1 ? 0 : 1
      } else {
        this.thumbMap[item.object_id] = true
        status = item.is_thumbs ? 2 : 1
        item.is_thumbs = +item.is_thumbs === 1 ? 0 : 1
        if (+item.is_thumbs === 1) {
          item.thumbs_num++
        } else {
          item.thumbs_num--
        }
      }
      let params = {
        object_id: item.object_id,
        handel_type: type,
        handel_status: status
      }

      thumbAndCollect(params)
        .then(() => {
          if (+status === 1) {
            this.showCollectDialog = true
            setTimeout(() => {
              this.showCollectDialog = false
            }, 2000)
          }
          setTimeout(() => {
            if (type === 'collect') {
              delete this.collectMap[item.object_id]
            } else {
              delete this.thumbMap[item.object_id]
            }
          }, 1000)
        })
        .catch(() => {
          if (type === 'collect') {
            item.is_collect = +item.is_collect === 1 ? 0 : 1
            delete this.collectMap[item.object_id]
          } else {
            item.is_thumbs = +item.is_thumbs === 1 ? 0 : 1
            if (+item.is_thumbs === 1) {
              item.thumbs_num--
            } else {
              item.thumbs_num++
            }
            delete this.thumbMap[item.object_id]
          }
          this.$message.error('操作失败，请重试~')
        })
    },
    // ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓详情模式↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
    // 获取详情
    getQuestionDetail({ object_id, s_p_t }) {
      this.zlaBtn = {
        key_name: '查看答疑',
        key_content: this.tabBtn[this.activeTab]
      }
      this.userInfo = {}
      this.questionDetail = []
      if (!object_id || +s_p_t !== 1) {
        return this.$message.warning('暂不支持查看该问题~')
      }
      this.clickLock = true
      let params = {
        object_id
      }
      if (this.activeTab === 1) {
        params.is_unread = 1
      }
      getQuestionDetail(params)
        .then(res => {
          // 处理问题详情列表
          let {
            data: {
              online_reply: { first_question, add_questions },
              user_info
            }
          } = res
          this.userInfo = user_info || {}
          first_question = first_question || {}
          add_questions = add_questions || []
          if (!first_question.questions) {
            this.$message.warning('暂不支持查看该问题~')
            return (this.clickLock = false)
          }
          // 把首次提问和追问的问题和回答放在一起,处理成一个数组
          // 处理只有首问的情况
          if (add_questions.length) {
            add_questions.unshift(first_question)
          } else {
            add_questions = [first_question]
          }
          // 拉平数组
          add_questions = add_questions
            .map(item => {
              item = [
                (Array.isArray(item.questions) && item.questions) || [],
                (Array.isArray(item.replys) && item.replys) || []
              ].flat()
              return item
            })
            .flat()
          // 处理回复创建时间,图片格式
          add_questions.forEach(item => {
            item.imgs_url =
              (Array.isArray(item.imgs_url) &&
                item.imgs_url.map(img => img.url)) ||
              (Array.isArray(item.reply_imgs_url) &&
                item.reply_imgs_url.map(img => img.url))
            item.create_time = item.create_time || item.reply_time
            item.create_time =
              (item.create_time &&
                this.timeFormat(
                  'Y-m-d H:i',
                  new Date(item.create_time.replace(/-/g, '/')).getTime() / 1000
                )) ||
              ''
          })
          this.questionDetail = add_questions
          this.showDetail = true
          this.clickLock = false
          this.$forceUpdate()
        })
        .catch(err => {
          this.$message.warning('网络慢,请刷新重试~')
          this.clickLock = false
        })
    },
    // 之了数据点击
    sendZlaClick() {
      this.keyClick({
        ...this.zlaBtn
      })
    }
  },
  watch: {
    keyId: {
      handler: function(val, oldVal) {
        this.init()
      },
      immediate: true
    },
    showDetail: {
      handler: function(val, oldVal) {
        if (!val) {
          this.init()
        }
      }
    },
    zlaBtn: {
      handler() {
        this.sendZlaClick()
      },
      deep: true
    }
  }
}
</script>

<style scoped>
.select-none {
  user-select: none;
}
.card-container {
  /* height: calc(100% - 60px); */
}
.dark-type.card-container {
  /* css-ignore */
  height: calc(100% - 34px);
}
.fixed-right {
  width: 420px;
  position: fixed !important;
  right: 24px;
  top: 90px;
  bottom: 10px;
  padding: 16px 0;
  background: #fff;
  border-radius: 10px;
  z-index: 9;
  box-shadow: -2px 4px 20px #e6e6e6;
  word-break: break-all;
}
.tab-container {
  padding: 16px 20px 0;
}
.overflow-scroll {
  margin-right: 4px;
  padding: 0 16px 0 20px;
  height: calc(100% - 66px);
  overflow-y: scroll;
  overflow-y: overlay;
  overflow-x: hidden;
}
.tab-btn {
  margin-right: 16px;
  height: 23px;
  font-size: 18px;
  font-weight: 500;
  color: #8c8c8c;
  line-height: 23px;
  cursor: pointer;
}
.dark-type .tab-btn.active-tab {
  /* css-ignore */
  color: #ffffff;
}
.tab-btn.active-tab {
  /* css-ignore */
  color: #383838;
}
.question-btn {
  margin-left: auto;
  width: 68px;
  height: 24px;
  font-size: 12px;
  color: #ffffff;
  line-height: 24px;
  text-align: center;
  background: #ff8d38;
  border-radius: 12px;
  cursor: pointer;
}

.no-data {
  margin-top: 104px;
  color: #b3b3b3;
}
.empty-img {
  display: block;
  width: 122px;
  height: 79px;
}
.empty-text {
  margin-top: 10px;
  text-align: center;
  width: 154px;
  height: 20px;
  line-height: 20px;
  font-size: 14px;
  font-family: 'PingFangSC-Regular, PingFang SC';
  font-weight: 400;
  color: #8c8c8c;
}
.back-btn {
  font-size: 18px;
  font-weight: 400;
  color: #383838;
  line-height: 23px;
}
.dark-type .back-btn {
  /* css-ignore */
  color: #ffffff;
}
.question-card {
  position: relative;
  display: block;
  width: 100%;
  margin-bottom: 12px;
  padding: 16px 12px;
  background: #fff;
  border-radius: 4px;
}
.dark-type .question-card {
  /* css-ignore */
  background: #333333;
}
.question-card.unread::after {
  content: '';
  position: absolute;
  top: 8px;
  right: 8px;
  width: 8px;
  height: 8px;
  background: #ff4d35;
  border-radius: 6px;
}
.card-title-info {
  font-size: 14px;
  font-weight: 400;
  color: #383838;
  text-align: start;
  line-height: 20px;
}
.dark-type .card-title-info {
  /* css-ignore */
  color: #b3b3b3;
}
.question-status {
  /* transform: translateY(-1px); */
  display: inline-block;
  padding: 0 8px;
  height: 18px;
  font-size: 10px;
  color: #ff7819;
  line-height: 16px;
  text-align: center;
  border-radius: 10px;
  border: 1px solid #ff8d38;
}
.question-status.blue-status {
  /* css-ignore */
  color: #3480ff;
  border: 1px solid #3480ff;
}
.card-teacher-header {
  width: 20px;
  height: 20px;
  border-radius: 50%;
}

.card-teacher-name {
  font-size: 12px;
  color: #bfbfbf;
  line-height: 17px;
}
.list-teacher-name {
  color: #383838;
}
.dark-type .list-teacher-name {
  /* css-ignore */
  color: #bfbfbf;
}
.card-teacher-tag {
  padding: 0 4px;
  height: 18px;
  font-size: 10px;
  color: #3480ff;
  line-height: 16px;
  background: #eff8ff;
  border-radius: 10px;
  /* border: 1px solid #3480ff; */
}
.dark-type .card-teacher-tag {
  background: #1c2d50;
}
.scale-83 {
  display: inline-block;
  transform: scale(0.83);
}
.card-teacher-tag.orange {
  /* css-ignore */
  background: transparent;
  color: #ff8d38;
  border: 1px solid #ff8d38;
}
.card-teacher-reply {
  text-align: start;
  font-size: 13px;
  color: #383838;
  line-height: 18px;
}
.dark-type .card-teacher-reply {
  /* css-ignore */
  color: #b3b3b3;
}
.card-bottom-info {
  margin-top: 16px;
  font-size: 12px;
  color: #8c8c8c;
  line-height: 17px;
}
.collect-thumb {
  transform: translateY(1px);
}
/* 详情部分 */
.detail-container {
  margin: 8px 16px 0 20px;
  padding: 16px 12px;
  border-radius: 4px;
}
.dark-type .detail-container {
  /* css-ignore */
  margin-top: 26px;
  background-color: #333;
}
.detail-question-text {
  white-space: pre-wrap;
  word-break: break-all;
  font-size: 14px;
  color: #383838;
  line-height: 20px;
}
.dark-type .detail-question-text {
  /* css-ignore */
  color: #ffffff;
}
.create-time {
  font-size: 12px;
  color: #8c8c8c;
  line-height: 17px;
}
.question-img {
  flex-shrink: 0;
  width: 72px;
  height: 72px;
  border-radius: 8px;
}
.dark-type .c-b3 {
  /* css-ignore */
  color: #b3b3b3;
}
.c-ff7819 {
  color: #ff7819;
}
.collect-dialog {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 10000;
}
.collect-dialog-box {
  /* width: 258px;
  height: 72px; */
  padding: 16px 24px 14px;
  background: #000000;
  border-radius: 12px;
  opacity: 0.8;
  font-size: 0;
}
.collect-dialog-box-font {
  font-size: 14px;
  color: #fafafa;
  line-height: 20px;
}
.color-ff8d {
  color: #ff8d38;
}
.mt16 {
  margin-top: 16px;
}
.dayi-title {
  padding: 0px 20px 10px;
  font-size: 20px;
  font-weight: 600;
  color: #666666;
  line-height: 28px;
}
.dayi-title::before {
  content: '';
  margin-right: 6px;
  display: inline-block;
  width: 3px;
  height: 24px;
  background: #02a9f4;
}
.close-img {
  position: absolute;
  width: 16px;
  height: 16px;
  top: 16px;
  right: 16px;
  z-index: 999;
}
</style>
